package com.romanito.andiview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.Matrix.ScaleToFit;

public class ImageView extends android.widget.ImageView {
	
	private int _bitmapWidth, _bitmapHeight;
	private float _zoom, _panX, _panY, _panAdjust;
	private RectF _rectImageView, _rectBitmap;

	public ImageView(Context context) {
		super(context);		
		_zoom = 1f;
		_bitmapWidth = _bitmapHeight = 0;
	}

	@Override
	public void setImageBitmap(Bitmap bm) {
		_bitmapWidth = bm.getWidth();
		_bitmapHeight = bm.getHeight();
		_zoom = 1;
		_panX = _panY = 0;
		_panAdjust = Math.min(getWidth(), getHeight());
		super.setImageBitmap(bm);
		setScaleType(ScaleType.FIT_CENTER);		
	}

	public int getBitmapWidth() {
		return _bitmapWidth;
	}

	public int getBitmapHeight() {
		return _bitmapHeight;
	}

	public void setZoom(float zoom) {
		_zoom = zoom;		
		applyMatrix();
	}

	public float getZoom() {
		return _zoom;
	}
	
	public boolean zoomBy(float zoomDelta) {
		if (zoomDelta < 0 || zoomDelta > 0 && _zoom < 30) {
			float newZoom = _zoom * (1 + zoomDelta);
			if (newZoom < 1)
				newZoom = 1;
			setZoom(newZoom);	
			return true;
		}
		else
			return false;
	}
	
	public void panBy(float deltaX, float deltaY) {
		_panX += deltaX * _panAdjust / _zoom;
		_panY += deltaY * _panAdjust / _zoom;
		applyMatrix();
	}

	private void applyMatrix() {
		
		float zoomDeltaX = (_bitmapWidth - _bitmapWidth / _zoom) / 2;
		float zoomDeltaY = (_bitmapHeight - _bitmapHeight / _zoom) / 2;

		_rectImageView = new RectF(0, 0, getWidth(), getHeight());
		_rectBitmap = new RectF(zoomDeltaX + _panX, zoomDeltaY + _panY, _bitmapWidth - zoomDeltaX + _panX, _bitmapHeight - zoomDeltaY + _panY);
		
		Matrix matrix = new Matrix();
		matrix.setRectToRect(_rectBitmap, _rectImageView, ScaleToFit.CENTER);
		setScaleType(ScaleType.MATRIX);		
		setImageMatrix(matrix);	
	}
}
